package com.piece.core.authentication.provider;

import com.piece.core.authentication.exception.UserNotMatchException;
import com.piece.core.web.authority.token.OpenIdAuthenticationToken;
import com.piece.core.framework.support.dto.UserDetailDTO;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;

public class AuthenticationOpenIdProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) {
        OpenIdAuthenticationToken authenticationToken = (OpenIdAuthenticationToken) authentication;
        String openId = (String) authenticationToken.getPrincipal();
        UserDetailDTO user = (UserDetailDTO) userDetailsService.loadUserByUsername(openId);
        if (null == user) {
            throw new UserNotMatchException();
        }

        OpenIdAuthenticationToken authenticationResult = new OpenIdAuthenticationToken(openId, user, user.getAuthorities(), authenticationToken.getClientId());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return OpenIdAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
